using System;
using System.Diagnostics;
using Clandestine.Graphics;
using Clandestine.Graphics.Text;

namespace Shlick
{
	public class ToolNameDisplay : Renderable
	{
		public MapDocument MapDocument { get; private set; }
		public ToolManager ToolManager { get { return this.MapDocument.ToolManager; } } 
		public TextSprite NameSprite;
		public TextSprite SelectedSprite; // shows whether a level/layer
		private bool selected = true; // gets whether we know it's selected yet so we know when it changes
		
		const float startAlpha = 0.7f;
		const float endAlpha = 0.15f;
		const float fadeTimePeriod = 1.5f;
		const float fadeConst = ((endAlpha - startAlpha) / fadeTimePeriod);
		
		Stopwatch sw = new Stopwatch();
		
		public ToolNameDisplay(MapDocument mapDocument, RenderList list) : base(list)
		{
			this.MapDocument = mapDocument;
				
			// Setup sprites
			NameSprite = Fonts.Default.DrawText(list, " ");
			NameSprite.Color = Color4.Black;
			NameSprite.Color.A = startAlpha;
			SelectedSprite = Fonts.Default.DrawText(list, " ");
			SelectedSprite.Color = Color4.Red;
			SelectedSprite.Color.A = startAlpha;
			SelectedSprite.Transform.Y = 20;
		}

		protected override void render()
		{
			// Check for updates
			if (NameSprite.Text != this.ToolManager.CurrentTool.Name)
				changeSpriteText(NameSprite, this.ToolManager.CurrentTool.Name);
			
			bool s2 = (this.ToolManager.ActiveLevel != null && this.ToolManager.ActiveLayer != null);
			if (selected != s2)
				this.changeSpriteText(SelectedSprite, s2 ? "" : "No Layer Selected"); selected = s2;
			
			// Fade
			fade(NameSprite);
			//fade(SelectedSprite);
			
			sw.Reset();
			sw.Start();
			
			// ts.Render() gets called by Graphics another time, as it is somewhere else in our RenderList.
		}
		
		protected void changeSpriteText(TextSprite sprite, string text)
		{
			// nasty little bit of code here, but .Text isn't meant to be set during a render!
			MapDocument.Graphics.WindowInternal.ReleaseContext();
			
			sprite.Color.A = startAlpha;
			sprite.Text = text;
			
			MapDocument.Graphics.WindowInternal.MakeContextCurrent();
		}
		
		protected void fade(TextSprite sprite)
		{
			if (sprite.Color.A > endAlpha)
			{
				sprite.Color.A += ((float) (fadeConst * sw.Elapsed.TotalSeconds));
				if (sprite.Color.A < endAlpha)
					sprite.Color.A = endAlpha;
			}
		}
	}
}
